<?php
use Illuminate\Support\Facades\Response as FacadesResponse;

/**
 * @author hongyang
 */

class LawyerController extends BaseArticleController {
	
    protected $layout = 'layouts.masterlv';

    /**
     * 显示律师搜索框
     */
    public function search()
    {
        $this->layout = View::make('layouts.master');
        $this->layout->content = View::make('lawyer.search');
    }

    /**
     * 罗列所有律师。
     * 
     * results:
     * - [lawyers]
     */
    public function listLawyers()
    {
        $input = Input::all();
        $cat_id = Input::get('cat_id', 0);
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $province_id = Input::get('province_id', null); 
        $city_id = Input::get('city_id', null); // Input::get('city_id', $this->getCityId($input));
        $district_id = Input::get('district_id', null);
        $q = Input::get('q', '');
        $offset = ($page-1) * $rows_per_page;
        $orderby = Input::get('order_by', 'user.score');
        $type = Input::get('type', Post::TYPE_PAY_TEXT);
        $direction = 'DESC';
        if ($orderby == 'price') {
            if ($type == Post::TYPE_PAY_PHONE) {
                $orderby = 'lawyer.phone_reply_fee';
            } else {
                $orderby = 'lawyer.text_reply_fee';
            }
            $direction = 'ASC';
        } elseif ($orderby == 'best_evaluated') {
            $orderby = 'lawyer.average_evaluate_score';
        } elseif($orderby == 'case_count'){
            $orderby = 'lawyer.case_count';
        }
        
        $experience = Input::get('experience', '');
        $is_recommended = Input::get('is_recommended');
        $rules = array(
            'cat_id' => 'numeric|min:1',
            'page' => 'numeric|min:1',
            'rows_per_page' => 'numeric|min:1',
            'city_id' => 'numeric|min:1',
            'district_id' => 'numeric|min:1'
        );

        $messages = array(
            'cat_id.numeric' => 'cat_id需要是数字',
            'cat_id.min' => 'cat_id不能少于1',
            'page.numeric' => 'page需要是数字',
            'rows_per_page.numeric' => 'rows_per_page需要是数字',
            'city_id.numeric' => 'city_id需要是数字',
            'district_id.numeric' => 'district_id需要是数字'
        );
        
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return FacadesResponse::json(array(
                "status_code" => 400,
                'error_messages' => $validator->errors()
            ), 400);
        }

        // 经过了验证
        try {
            $lawyers = Lawyer::getLawyers(
                $cat_id, 
	    $province_id, 
                $city_id, 
                $district_id,
                $q, 
                $experience,
                $offset, 
                $rows_per_page, 
                $created_at = NULL, 
                $orderby, 
                $direction,
                $is_recommended);
            $lawyerArr = $lawyers->toArray();
            
            // 显示下面的fields
            $whitelist = array(
                'id',
                'user_id', 
                'avatar', 
                'score', 
                'likes_count',
                'collects_count',
                'created_at',
                'updated_at',
                'status',  
                'realname',
                'province', 
                'city', 
                'district', 
                'address', 
                'nikname',
                'introduce',
                'experience',
                'work_scope', 
                'practice_period',
                'case_count',
                'service_time',
                'bg_image', 
                'is_recommended',
                'follows_count',
                'average_evaluate_score',
                'position',
                'free_reply_count',
                'pay_reply_count',
                'text_reply_fee',
                'phone_reply_fee',
                'is_following',
                'company_name'
            );
            $whitelist = array_flip($whitelist);
            foreach($lawyerArr as &$lawyer) {
                $lawyer = array_intersect_key($lawyer, $whitelist);
                $lawyer['province'] = AreaHelper::areaCodeToName($lawyer['province']);
                $lawyer['city'] = AreaHelper::areaCodeToName($lawyer['city']);
                $lawyer['district'] = AreaHelper::areaCodeToName($lawyer['district']);
                $lawyer['work_scope'] = UtilsHelper::getActualWorkScopes($lawyer['work_scope']);
                $lawyer['avatar'] = UtilsHelper::getImage($lawyer['avatar'], "img/dfimg.png");
                $lawyer['practice_period'] = UtilsHelper::getPracticePeriodStr($lawyer['practice_period']);
                $lawyer['follower_count'] = $this->getFollowerCount($lawyer['id']);
                $lawyer['average_evaluate_score'] = number_format($lawyer['average_evaluate_score'],1);
                $lawyer['position'] = UtilsHelper::getPositionStr($lawyer['position']);
                $lawyer['is_following'] = Follow::isFollowing($lawyer['id']);
                $lawyer['text_reply_fee'] = $lawyer['text_reply_fee'];
                $lawyer['phone_reply_fee'] = $lawyer['phone_reply_fee'];
                $lawyer['id'] = $lawyer['user_id']; 
            }
            return $this->makeView('lawyer.list', $lawyerArr);
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '咨询律师失败，请稍后再试。',
                503
            );
        }
    }
    
    public function listContainer()
    {
        $workScopeList = UtilsHelper::workScope();
        $getPracticePeriods = UtilsHelper::getPracticePeriods();
        $cities = UtilsHelper::getCities();
        $listOrders = self::getListOrders();
        $city_id = Input::get('city_id', $this->getCityId(Input::all()));
        $this->layout = View::make('layouts.master');
        $this->layout->content = View::make( 
            'lawyer.list_container', 
            array(
                'workscopes' => $workScopeList,
                'practisePeriods' => $getPracticePeriods,
                'cities' => $cities,
                'listOrders' => $listOrders,
                'city_id' => $city_id
            )
        );
    }

    /**
     * 从不同的地方获取city_id
     * - 提交的参数
     * - session
     * - 淘宝的地域信息服务
     *
     * @param array $input
     *            用户提交的数据
     */
    private function getCityId($input)
    {
        if (isset($input['city_id']) && $input['city_id']) {
            $city_id = $input['city_id'];
        } else {
            if (Session::get('city_id')) {
                $city_id = Session::get('city_id');
            } else {
                $area = UtilsHelper::get_client_city_info_by_taobao_service();
                $city_id = $area['city_id'];
            }
        }
        Session::put('city_id', $city_id);
        return $city_id;
    }

    /**
     * 浏览律师详细情况
     *
     * @param integer $id            
     */
    public function view($id)
    {
        $user = $this->getLawyer($id);
        if (! is_a($user, 'User')) {
            return $user;
        }
        $userArr = $this->transformWorkScopes($user->toArray());
// 已有关注：59
// 站内等级：中级
// 服务评价：1 2 3 4 5
// 服务单价：图文资讯和电话咨询
        $data = [];
        $data['realname'] = $userArr['realname'];
        $data['id'] = $userArr['id'];
        $data['signature'] = $userArr['signature'];
        $data['average_evaluate_score'] = number_format($userArr['lawyer']['average_evaluate_score'], 1);
        $default = "img/lawyer/lawyer_bg.png";
        $data['bg_img'] = UtilsHelper::getImage($user->lawyer->bg_image, $default);
        $data['avatar'] = UtilsHelper::getImage($user->avatar, "img/dfimg.png");
        $data['company_name'] = $userArr['lawyer']['company_name'];
        $data['practice_period'] = UtilsHelper::getPracticePeriodStr($userArr['lawyer']['practice_period']);
        $data['work_scope'] = $userArr['lawyer']['work_scope'];
        $data['introduce'] = $userArr['lawyer']['introduce'];
        $data['experience'] = $userArr['lawyer']['experience'];
        $data['task_count'] = $this->getFinishedTaskCount($id);             // 已完成服务
        $data['follower_count'] = $this->getFollowerCount($id);             // 被关注次数
        $data['reward_count'] = WalletTransaction::rewardCount($id);
        $data['likes_count'] = $userArr['likes_count'];
        $data['score'] = $user->score;
        $data['level'] = $this->calculateLawyerLevel($data);
        $data['text_reply_fee'] = $userArr['lawyer']['text_reply_fee'];
        $data['phone_reply_fee'] = $userArr['lawyer']['phone_reply_fee'];
        $data['license_id'] = $userArr['lawyer']['license'];
        $data['law_cases'] = $userArr['lawyer']['law_cases'];
        $data['address'] = $user->address;
        $data['city'] = AreaHelper::areaCodeToName($userArr['city']);
        $data['district'] = AreaHelper::areaCodeToName($userArr['district']);
        $data['province'] = AreaHelper::areaCodeToName($userArr['province']);

        if (Auth::check()) {
            $data['is_following'] = Follow::isFollowing($userArr['id']);
            $data['is_like'] = $user->isLiked();
        } else {
            $data['is_following'] = null;
            $data['is_like'] = null;
        }
        $this->layout = View::make('layouts.master');
        return $this->makeView('lawyer.view', $data);
    }
    /**
     * 认证律师：通过律师认证
     * 初级律师：从业1年以上，获得积分1000以上，接到订单1个以上
     * 中级律师：从业1年以上，获得积分5000以上，接到订单10个以上
     * 高级律师：从业5年以上，获得积分10000以上，接到订单100个以上
     */
    protected function calculateLawyerLevel($data) 
    {
        $level = "认证律师";
        if ($data['score'] >= 1000 || $data['task_count'] >= 1) {
            $level = "初级律师";
        }
        if ($data['score'] >= 5000 || $data['task_count'] >= 10) {
            $level = "中级律师";
        }
        if (in_array($data['practice_period'], array('5-8年', '10年以上')) || $data['score'] >= 10000 || $data['task_count'] >= 100) {
            $level = "高级律师";
        }
        return $level;
    }

    public function getFollowerCount($id)
    {
        return Follow
            ::where('follow_stat', Follow::FOLLOWED)
            ->where('follow_id', $id)
            ->count();
    }

    /**
     * Todo: 应该包括免费和付费的咨询
     */
    public function getFinishedTaskCount($id)
    {
        // 暂时只显示已经回复了的咨询
        return Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id')
            ->where('posts.status', Post::STATUS_COMPLETE)
            ->where('post_thread.user_id', $id)
            ->count();
    }

    public function questions($id) {
        $page = Input::get('page', 1);
        $order = Input::get('order', 'created_at');
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page-1) * $rows_per_page;

        $user = $this->getLawyer($id);
        if (! is_a($user, 'User')) {
            return $user;
        }
        $questions = Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->select(
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.creator_id',
                'user.avatar as creator_avatar',
                'user.realname as creator_realname',
                'posts.created_at',
                'posts.updated_at')
            ->where('post_thread.user_id', $id)
            ->orderBy($order, 'DESC')
            ->take($rows_per_page)
            ->skip($offset)
            ->get();
        $questionArr = $questions->toArray();
        $questionArr = $this->addComments($questionArr);
        return $this->makeView('lawyer.questions', $questionArr);
    }

    /**
     * 把相关的评论以及评论的用户加到咨询的列表中去
     */
    protected function addComments($questions) {
        foreach($questions as $key => $question) {
            $comments = Comment
                ::leftJoin('user', 'user.id', '=', 'comments.creator_id')
                ->select(
                    'comments.id',
                    'comments.content',
                    'user.realname as creator_realname',
                    'user.avatar as creator_avatar',
                    'user.id as creator_id',
                    'comments.created_at'
                )
                ->where('comments.post_id', $question['id'])
                ->orderBy('created_at', 'DESC')
                ->get();
            $question['comments'] = $comments->toArray();
            foreach($question['comments'] as &$comment) {
                $comment['creator_avatar'] = UtilsHelper::getImage($comment['creator_avatar'], "img/dfimg.png");
            }
            $question['creator_avatar'] = UtilsHelper::getImage($question['creator_avatar'], "img/dfimg.png");
            $questions[$key] = $question;
        }
        return $questions;
    }

    /**
     * 验证输入数据，返回错误信息或者获取的数据
     *
     * @param integer $id            
     * @return \Illuminate\Http\JsonResponse|unknown
     */
    protected function getLawyer($user_id)
    {
        // validation
        $rules = array(
            'user_id' => 'exists:lawyer,user_id'
        );
        $messages = array(
            'user_id.exists' => '这个律师不存在'
        );
        $validator = Validator::make(array(
            'user_id' => $user_id
        ), $rules, $messages);
        
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.404', 
                $validator->errors(), 404);
        }
        
        $user = User::find($user_id);
        $user->load('lawyer');
        return $user;
    }

    protected function transformWorkScopes($userArr) {
        $workScopeStr = $userArr['lawyer']['work_scope'];
        $workScopeArr = [];
        $originalWorkScopeArr = explode(",", $workScopeStr);
        foreach($originalWorkScopeArr as $workScope) {
            $value = UtilsHelper::getWorkScopeName($workScope);
            if ($value) {
                $workScopeArr[] = ['key' => $workScope, 'value' => UtilsHelper::getWorkScopeName($workScope)];
            }
        }
        $userArr['lawyer']['work_scope'] = $workScopeArr;
        return $userArr;
    }

    /**
     * 获取用户对律师的评价
     */
    public function evaluations($id)
    {
        $user = $this->getLawyer($id);
        if (! is_a($user, 'User')) {
            return $user;
        }

        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page-1) * $rows_per_page;
        $rules = array (
            'page' => 'numeric|min:1',
            'rows_per_page' => 'numeric|min:1',
        );

        $messages = array(
            'page.numeric' => 'page需要是数字',
            'rows_per_page.numeric' => 'rows_per_page需要是数字',
        );
        $validator = Validator::make ( Input::all(), $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        $evaluations = Evaluate::leftJoin('posts', 'evaluate.item_id', '=', 'posts.id')
            ->leftJoin('user', 'user.id', '=', 'evaluate.creator_id')
            ->leftJoin('post_thread', 'post_thread.post_id', '=', 'posts.id')   // 通过post_thread找到抢单成功的律师
            ->select(
                'user.id as creator_id',
                'user.realname as creator_realname',
                'user.avatar as creator_avatar',
                'evaluate.created_at as evaluate_created_at',
                'evaluate.score as evaluate_score',
                'evaluate.comment as evaluate_comment',
                'evaluate.tags as evaluate_tags')
            ->where('posts.status', Post::STATUS_COMPLETE)
            ->where('post_thread.user_id', $id)
            ->orderBy('evaluate.created_at', 'DESC')
            ->take($rows_per_page)
            ->skip($offset)
            ->get();

        $evaluationsArr = $evaluations->toArray();
        foreach($evaluationsArr as &$evaluate) {
            $evaluate['creator_avatar'] = UtilsHelper::getImage($evaluate['creator_avatar'], "img/dfimg.png");
            if (isset($evaluate['evaluate_tags'])) {
                $evaluate['evaluate_tags'] = explode(',', $evaluate['evaluate_tags']);
                foreach($evaluate['evaluate_tags'] as &$tag) {
                    $tag = ["key" => $tag, "value" => Evaluate::getTagName($tag)];
                }
            } else {
                $evaluate['evaluate_tags'] = [];
            }
        }
        return $this->makeView('lawyer.evaluations', $evaluationsArr);
    }

    /**
     * 获取律师的成交记录
     * 
     * 显示：价格，数量，付款时间，产品类型
     */
    public function deals($id)
    {
        $user = $this->getLawyer($id);
        if (! is_a($user, 'User')) {
            return $user;
        }

        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page-1) * $rows_per_page;
        $rules = array (
            'page' => 'numeric|min:1',
            'rows_per_page' => 'numeric|min:1',
        );

        $messages = array(
            'page.numeric' => 'page需要是数字',
            'rows_per_page.numeric' => 'rows_per_page需要是数字',
        );
        $validator = Validator::make ( Input::all(), $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        $deals = WalletTransaction::where('user_id', $id)->where('type', WalletTransaction::TYPE_QUESTION)->where('direction', WalletTransaction::DIRECTION_IN)
	            ->orderBy('created_at', 'DESC')
	            ->take($rows_per_page)
	            ->skip($offset)
	            ->get();
        $dealsArr = $deals->toArray();
         foreach($dealsArr as &$deal) {
         	$order = Order::find($deal['associate_id']);
         	if($order){
         		$user = User::find($order->user_id);
         		$deal['qty'] = $order->qty;
         		$post_id = PostOrder::where('order_id', $order->id)->first()->post_id;
         		$post = Post::find($post_id);
         		$deal['type'] = $post?$post->getType():'';
         		$deal['creator_avatar'] = UtilsHelper::getImage($user->avatar, "img/dfimg.png");
             	$deal['creator_name'] = $user->getUserName();
         	}
         }
        return $this->makeView('lawyer.evaluations', $dealsArr);
    }


    /**
     * 获取用户对所有律师的评价
     */
    public function allEvaluations()
    {
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page-1) * $rows_per_page;
        $rules = array (
            'page' => 'numeric|min:1',
            'rows_per_page' => 'numeric|min:1',
        );

        $messages = array(
            'page.numeric' => 'page需要是数字',
            'rows_per_page.numeric' => 'rows_per_page需要是数字',
        );
        $validator = Validator::make ( Input::all(), $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        $evaluations = Evaluate::leftJoin('posts', 'evaluate.item_id', '=', 'posts.id')
            ->leftJoin('user', 'user.id', '=', 'evaluate.creator_id')
            ->select(
                'user.id as creator_id',
                'user.realname as creator_realname',
                'user.avatar as creator_avatar',
                'evaluate.created_at as evaluate_created_at',
                'evaluate.score as evaluate_score',
                'evaluate.comment as evaluate_comment')
            ->where('posts.status', Post::STATUS_COMPLETE)
            ->orderBy('evaluate.created_at', 'DESC')
            ->take($rows_per_page)
            ->skip($offset)
            ->get();

        $evaluationsArr = $evaluations->toArray();
        foreach($evaluationsArr as &$evaluate) {
            $evaluate['creator_avatar'] = UtilsHelper::getImage($evaluate['creator_avatar'], "img/dfimg.png");
        }
            
        return $this->makeView('home.evaluations', $evaluationsArr);
    }

    protected function getArticlesFromLawyer($id)
    {
        $user = $this->getLawyer($id);
        if (! is_a($user, 'User')) {
            return $user;
        }

        $q = Input::get('q', '');
        $page = Input::get('page', 1);
        $order = Input::get('order', 'created_at');
        $cat_id = Input::get('cat_id', 0);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page-1) * $rows_per_page;

        $rules = array (
            'cat_id' => 'numeric|min:1',
            'page' => 'numeric|min:1',
            'rows_per_page' => 'numeric|min:1',
        );

        $messages = array(
            'cat_id.numeric' => 'cat_id需要是数字',
            'cat_id.min' => 'cat_id不能少于1',
            'page.numeric' => 'page需要是数字',
            'rows_per_page.numeric' => 'rows_per_page需要是数字',
        );
        $validator = Validator::make ( Input::all(), $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        $articles = Article::getArticles(
            [Article::TYPE_INFO,Article::TYPE_LAW,Article::TYPE_CASE,Article::TYPE_LIBRARY,Article::TYPE_DOCUMENT], 
            $q, 
            $cat_id, 
            $offset, 
            $rows_per_page,
            $order_by = $order,
            $visibility = Article::VISIBILITY_ALL,
            $days = null, 
            $status = Article::STATUS_APPROVED, 
            $from_admin = 0, 
            $creator_id = $user->id
        );
        $data = $articles->toArray();
        for($i=0;$i<count($data);$i++){
            $classname = ArticleClass::find($data[$i]['law_cat']);
            if(empty($classname)){
                $data[$i]['classname'] = '未分类';
            }else{
                $data[$i]['classname'] = $classname->name;
            }
            $default= "img/default_imgs/[]".rand(1,19).".png";
            $data[$i]['img'] = UtilsHelper::getImage($data[$i]['img'],$default);
            $data[$i]['avatar'] = UtilsHelper::getImage($data[$i]['avatar'],"img/dfimg.png");
        }
        return $data;
    }

    /**
     * 获取某个律师分享的文章
     */
    public function articles($id)
    {
        $articles = $this->getArticlesFromLawyer($id);
        return $this->makeView('lawyer.articles', $articles);
    }
    
    /**
     * 获取律师分享的最新文章
     */ 
    public function allArticles()
    {
    	$q = Input::get('q', '');
    	$page = Input::get('page', 1);
    	$rows_per_page = Input::get('rows_per_page', 3);
    	$offset = ($page-1) * $rows_per_page;
    
    	$rules = array (
    			'cat_id' => 'numeric|min:1',
    			'page' => 'numeric|min:1',
    			'rows_per_page' => 'numeric|min:1',
    	);
    
    	$messages = array(
    			'cat_id.numeric' => 'cat_id需要是数字',
    			'cat_id.min' => 'cat_id不能少于1',
    			'page.numeric' => 'page需要是数字',
    			'rows_per_page.numeric' => 'rows_per_page需要是数字',
    	);
    	$validator = Validator::make ( Input::all(), $rules, $messages );
    	if ($validator->fails()) {
    		// the given data did not pass validation
    		return $this->makeView(
    				'errors.400',
    				$validator->errors(),
    				400
    		);
    	}

    	$articles = Article::getAllArticles(
			$offset,
			$rows_per_page,
			$order_by = 'created_at',
			$visibility = 0,
			$status = Article::STATUS_APPROVED,
			$from_admin = 0
    	);
        $articleArr = $articles->toArray();
        foreach($articleArr as $key => &$article) {
        	$default= "img/default_imgs/[]".rand(1,19).".png";
            $article['img'] = UtilsHelper::getImage($article['img'],$default);
            $article['avatar'] = UtilsHelper::getImage($article['avatar'],"img/dfimg.png");
            
        }
    	return $this->makeView('home.index', $articleArr);
    } 
	
    /*
     * 查看文章内容
     */
    public function viewArticle($id){
    	return $this->articleView($id, 'news.view');
    }

    /**
     * 获取某个律师的成交纪录
     */
    public function orders($id)
    {
		try{
			$order = Order::lawyerOrder(Order::STATE_PAID, $id);
		}catch (Exception $ex){
    		Log::error($ex);
    		return $this->makeView(
    				'errors.503',
    				'服务器暂时无法响应，请稍后再试',
    				503
    			);
    	}
    	dd($order->toArray());
    	return $this->makeView('lawyer.view',$order->toArray());
    }

    /**
     * 获取某个律师的经典案例 ［不确定］
     */
    public function cases($id)
    {
        $user = $this->getLawyer($id);
        if (! is_a($user, 'User')) {
            return $user;
        }
        $user->load('cases');
        return $this->makeView('lawyer.cases', $user->toArray());
    }

    public function workscopes()
    {
        $workScopeList = UtilsHelper::workScope();
        return $this->makeView('lawyer.workscopes', $workScopeList);
    }

    public function practisePeriods()
    {
        $practicePeriods = UtilsHelper::getPracticePeriods();
        return $this->makeView('lawyer.practise_periods', $practicePeriods);
    }

    protected function getListOrders()
    {
        return array(
            'most_popular' => '人气最高',
            'best_evaluated' => '评分最好',
            'experience' => '执业年限',
            'pay_reply_count' => '接单数'
        );
    }

    /**
     * 获取城市列表，按照城市里面律师的多少排序
     */
    public function getCitiesFromLawyer()
    {
        $cities = User::where('user_group_id', 2)
            ->where('city', '!=', 'null')
            ->select(
                'city as city_code', 
                DB::raw('count(*) as lawyer_count')
            )
            ->groupBy('city_code')
            ->orderBy('lawyer_count', 'DESC')
            ->get();

        $citiesArr = $cities->toArray();
        foreach($citiesArr as &$city) {
            switch($city['city_code']) {
                case '310100':
                    $city['city_name'] = '上海市';
                break;
                case '500100':
                    $city['city_name'] = '重庆市';
                break;
                default:
                    $city['city_name'] = AreaHelper::areaCodeToName($city['city_code']);
            }
        }

        return $this->makeView('lawyer.cities', $citiesArr);
    }
}
